package com.guli.gulimall.cart.interceptor;

import com.guli.common.constant.AuthServerConstant;
import com.guli.common.constant.CartConstant;
import com.guli.common.vo.MemberResponseVo;
import com.guli.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法钱，判断用户的状态。并封装，传递给controller目标请求
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    //缓存 map<Thread,UserInfoTo>,线程隔离，方便同一线程用户数据获取
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行前运行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //登录了
            userInfo.setUserId(member.getId());
        }
        //未登录
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE)) {
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                }
            }
        }
        //如果没有临时用户，就分配临时用户
        if(StringUtils.isEmpty(userInfo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfo.setUserKey(uuid);
        }
        //目标方法执行之前
        threadLocal.set(userInfo);
        return true;
    }

    /**
     * 目标方法执行后运行，分配临时用户，让浏览器保存cookie
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUser()){
            //--持续的延长临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");//作用域
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);//过期时间
            response.addCookie(cookie);
        }
    }
}
